import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:wallet_utils/base_router_config.dart';
import 'package:wallet_utils/event_bus_utils.dart';
import 'package:wallet_utils/login_utils.dart';
import 'package:wallet_utils/msg_event_utils.dart';
import 'package:wallet_utils/report_widget/base/callback/base_callback.dart';
import 'package:wallet_utils/report_widget/loading_utils.dart';
import 'package:wallet_utils/timer_count_down.dart';
import 'package:wallet_utils/toast.dart';

import '../api/login_api.dart';
import 'bean/LoginBean.dart';
import 'state.dart';

class SmsPageLogic extends GetxController {
  final SmsPageState state = SmsPageState();
  bool isFirst = false;

  @override
  void onInit() {
    super.onInit();
    if (Get.arguments != null) {
      isFirst = Get.arguments['isFirst'];
    }
    state.timerCountDownWidget = TimerCountDownWidget(
      isOnTap: state.mobile.length >= 11,
      onTimerFinish: () {},
      onTap: () async {
        if (state.isAgreeUserPrivary) {
          return true;
        } else {
          ToastUtils.showToast('请勾选并阅读协议');
          return false;
        }
      },
      onClickGetSmsCode: () {
        //获取验证码
        getSmsCode();
      },
      isTextColor: state.mobile.length >= 11,
    );
  }

  //获取账号密码输入框焦点
  void requestAccountFocus(FocusNode mobileFocusNode, FocusNode pwdFocusNode) {
    mobileFocusNode.addListener(() {
      if (!mobileFocusNode.hasFocus) {
        //失去焦点
        state.isAccountFocus = false;
      } else {
        //获得焦点
        state.isAccountFocus = true;
      }
    });

    pwdFocusNode.addListener(() {
      if (!pwdFocusNode.hasFocus) {
        //失去焦点
        state.isPwdFocus = false;
      } else {
        //获得焦点
        state.isPwdFocus = true;
      }
    });
    update();
  }

  //判断是否可以登录
  void allowLogin(TextEditingController mobileController, TextEditingController pwdController) {
    state.mobile = mobileController.text;
    state.pwd = pwdController.text;
    if (state.mobile.isNotEmpty && state.pwd.isNotEmpty) {
      state.allowLogin = true;
    } else {
      state.allowLogin = false;
    }
    if (mobileController.text.isNotEmpty) {
      state.showDeleteIcon = true;
    } else {
      state.showDeleteIcon = false;
    }
    update();
  }

  deleteAccount() {
    state.mobileController.clear();
    state.showDeleteIcon = false;
    state.allowLogin = false;
    state.mobile = state.mobileController.text;
    //设置获取验证码颜色为灰色  并且不可点击
    state.timerCountDownWidget.changeTextColor(false);
    state.timerCountDownWidget.textIsTap(false);
    update();
  }

  //用户隐私协议选中或未选中
  void updateUserPrivary() {
    state.isAgreeUserPrivary = !state.isAgreeUserPrivary;
    update();
  }

  //获取验证码接口
  void getSmsCode() async {
    LoginApi.getSms(
        state.mobileController.text,
        BaseCallback(
            onSuccess: (map) {},
            onError: (msg) {
              Future.delayed(const Duration(milliseconds: 500), () {
                ToastUtils.showToast(msg ?? "");
              });
            }));
  }

  //验证码登录
  void mobileLogin() async {
    LoginApi.mobileLogin(
        state.mobileController.text,
        state.smsCodeController.text,
        BaseCallback(onSuccess: (map) {
          Get.back();
          LoginBean loginBean = LoginBean.fromJson(map);
          if (loginBean.data != null) {
            LoginUtils.setAuthorization(loginBean.data?.token ?? '');
            LoginUtils.saveLoginBean(jsonEncode(loginBean.toJson()));
            num? loginStatus = loginBean.data?.loginStatus;
            if (loginStatus == 1 || loginStatus == 2) {
              //已设置密码
              jumpPage();
            } else {
              //未设置密码
              // Get.toNamed(BaseRouterConfig.settingPwd);
              // Get.offNamed(BaseRouterConfig.main);
              jumpPage();
            }
          }
        }, onError: (msg) {
          Future.delayed(const Duration(milliseconds: 500), () {
            Get.back();
            ToastUtils.showToast(msg ?? "");
          });
        }));
  }

  void jumpPage() {
    FocusManager.instance.primaryFocus?.unfocus();
    if (!isFirst) {
      Get.back();
      EventBusUtils.getInstance()
          .fire(MsgEventBusUtils(MsgEventBusUtils.upHomeStatus, value: false));
      Get.until((route) => (route.settings.name == BaseRouterConfig.main));
    } else {
      Get.offNamed(BaseRouterConfig.main);
    }
  }

  void login() {
    if (state.mobileController.text.isNotEmpty && state.smsCodeController.text.isNotEmpty) {
      if (state.isAgreeUserPrivary) {
        LoadingUtils.showLoading(Get.context!, isCanBack: false);
        mobileLogin();
      } else {}
    }
  }
}
